<?php
namespace App\Admin\Controllers\CustomerDelivery;

use App\Importer\CustomerDelivery\CnImporter;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerDeliveryLogistics;
use App\Models\Basics\ExpressChannel;
use App\Models\Basics\ExpressCompany;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class DeliveryAbroadUploadController extends AdminController{

    protected $title = '海外发货单';

    protected function grid()
    {
        $type = request('type');
        return view('customer-delivery.delivery-abroad-upload.index',compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    /**
     * 上传平台物流信息
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importLogistics(UploadedFile $file)
    {
        DB::beginTransaction();
        try {
            $data = Excel::toArray(new CnImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false, 'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            foreach($data as $row){

                $count++;
                $_deliveryNo = $row[0] ? trim($row[0]) : '';
                $expressCompanyId = $row[1] ? intval(trim($row[1])) : 0;
                $expressChannelId = $row[2] ? intval(trim($row[2])) : 0;
                $trackingNo = $row[3] ? trim($row[3]) : '';
                $totalWeight = $row[4] ? trim($row[4]) : 0;
                $shippingFee = $row[5] ? trim($row[5]) : 0;
                $otherFee = $row[6] ? trim($row[6]) : 0;
                $deliveredAt = $row[7] ? RExcel::toDateTime(trim($row[7])) : date('Y-m-d H:i:s');
                $arrivedAt = $row[8] ? RExcel::toDateTime(trim($row[8])) : date('Y-m-d H:i:s');
                if(!$_deliveryNo || !$expressCompanyId || !$expressChannelId){
                    $errors[$count] = ',必填项为空';
                    continue;
                }

                $deliveryNo = strtoupper($_deliveryNo);
                if(!in_array($deliveryNo, $arr)){
                    $arr[$count] = $deliveryNo;
                }else{
                    $errors[$count] = ',重复记录';
                    continue;
                }
                if($deliveredAt || $arrivedAt){
                    if(!strtotime($deliveredAt)){
                        $errors[$count] = ",发货日期：".$deliveredAt."格式有误";
                        continue;
                    }
                    if(!strtotime($arrivedAt)){
                        $errors[$count] = ",到货日期：".$arrivedAt."格式有误";
                        continue;
                    }
                }
                $expressCompanyIdFlag = ExpressCompany::existById($expressCompanyId);
                if(!$expressCompanyIdFlag){
                    $errors[$count] = $expressCompanyId.',系统不存在该物流公司';
                    continue;
                }
                $expressChannelIdFlag = ExpressChannel::existById($expressChannelId);
                if(!$expressChannelIdFlag){
                    $errors[$count] = $expressChannelId.',系统不存在该物流渠道';
                    continue;
                }
                $deliveryObj = CustomerDelivery::query()->where('order_no', $deliveryNo)->first();
                if(!$deliveryObj){
                    $errors[$count] = $_deliveryNo.',发货单不存在';
                    continue;
                }

                $logisticsFeeStatus = CustomerDeliveryDetail::LOGISTICS_FEE_NO; //0
                if (intval($totalWeight) > 0 || intval($shippingFee) > 0 || intval($otherFee) > 0) {
                    //物流费用是否更新 (0:待更新 1:已更新)
                    $logisticsFeeStatus = CustomerDeliveryDetail::LOGISTICS_FEE_YES;
                }
                $syncStatus = CustomerDeliveryDetail::SYNC_STATUS_NO; //0
                if($trackingNo){
                    //物流追踪号是否同步 (0:未同步 1:已同步)
                    $syncStatus = CustomerDeliveryDetail::SYNC_STATUS_YES;
                }

                //更新发货明细
                $detailObj = CustomerDeliveryDetail::query()
                    ->where('order_no',$deliveryObj->order_no)
                    ->update([
                        'tracking_no' => $trackingNo,
                        'total_weight' => $totalWeight ?? 0,
                        'shipping_fee' => $shippingFee ?? 0,
                        'other_fee' => $otherFee ?? 0,
                        'delivered_at' => date('Y-m-d H:i:s',strtotime($deliveredAt)) ?? date('Y-m-d H:i:s',time()),
                        'sync_status' => $syncStatus,
                        'logistics_fee_status' => $logisticsFeeStatus
                    ]);
                if(!$detailObj){
                    $errors[$count] = $_deliveryNo.',物流录入失败2(发货单明细异常)';
                    continue;
                }

                //更新发货物流
                $logisticsObj = CustomerDeliveryLogistics::query()
                    ->firstOrNew([
                        'delivery_no' => $deliveryObj->delivery_no,
                        'order_no' => $deliveryObj->order_no
                    ]);
                $logisticsObj->area_id = $deliveryObj->area_id;
                $logisticsObj->express_company_id = $expressCompanyId ? intval($expressCompanyId) : 0;
                $logisticsObj->express_channel_id = $expressChannelId ? intval($expressChannelId) : 0;
                if($trackingNo) $logisticsObj->tracking_no = $trackingNo;
                if($totalWeight) $logisticsObj->total_weight = $totalWeight ?? 0;
                if($shippingFee) $logisticsObj->shipping_fee = $shippingFee ?? 0;
                if($otherFee) $logisticsObj->other_fee = $otherFee ?? 0;
                if($deliveredAt) $logisticsObj->delivered_at = date('Y-m-d H:i:s',strtotime($deliveredAt)) ?? date('Y-m-d H:i:s',time());
                if($arrivedAt) $logisticsObj->arrived_at = date('Y-m-d H:i:s',strtotime($arrivedAt)) ?? date('Y-m-d H:i:s',time());
                if(!$logisticsObj->save()){
                    $errors[$count] = $_deliveryNo.',物流录入失败3(发货单物流异常)';
                    continue;
                }

                //更新发货单
                $deliveryObj->logistics_status = 2; //物流状态 (1:待更新 2:已更新)
                $deliveryObj->delivered_at = date('Y-m-d H:i:s',strtotime($deliveredAt)) ?? date('Y-m-d H:i:s',time());
                if(!$deliveryObj->save()){
                    $errors[$count] = $_deliveryNo.',物流录入失败1(发货单异常)';
                    continue;
                }
            }

            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常!'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
